/*
 * ProcesoServer.cpp
 *
 * Author: Grupo Nro.
 */

#include "ProcesoServer.h"
#include "Properties.h"
#define CAMP_DIR "campanias/"

ProcesoServer::ProcesoServer() {
}

ProcesoServer::~ProcesoServer() {
}

bool ProcesoServer::leoFin() {
	char caracter;
	cin >> caracter;

	if (caracter == FIN_MA || caracter == FIN_MI) {
		return true;
	}

	return false;
}


void ProcesoServer::comenzarServer() {
	Properties properties;
	int puerto = properties.getPropertyAsInt("puerto");
	int puertoEnvio = properties.getPropertyAsInt("puerto.envio");
	ServerSocket * serverSocket = new ServerSocket(puerto);
	ServerSocket * serverSocketEnvio = new ServerSocket(puertoEnvio);
	Mutex * mutex = new Mutex();
	ServerThread serverThread(mutex, serverSocket, serverSocketEnvio);
	serverThread.start();

	while (!leoFin() && !serverThread.getMorir()) {
		serverThread.sleepThread(0);
	}

	//Morir hilo
	serverThread.setMorir(true);
	int reception_sockfd = serverSocket->getSockfd();
	ServerSocket::shutdownConexion(reception_sockfd);
	int send_sockfd = serverSocketEnvio->getSockfd();
	ServerSocket::shutdownConexion(send_sockfd);
	serverThread.join();
	reception_sockfd = serverSocket->getSockfd();
	ServerSocket::matarConexion(reception_sockfd);
	send_sockfd = serverSocketEnvio->getSockfd();
	ServerSocket::matarConexion(send_sockfd);

	//Liberar recursos
	if (serverSocket != NULL) {
		delete serverSocket;
		serverSocket = NULL;
	}
	if (serverSocketEnvio != NULL) {
	    delete serverSocketEnvio;
	    serverSocketEnvio = NULL;
	}
	if (mutex != NULL) {
		delete mutex;
		mutex = NULL;
	}
}

